package com.hzzftech.watchdog.busi.module.dingding.service.impl;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.hzzftech.watchdog.busi.constants.BusiConstant;
import com.hzzftech.watchdog.busi.module.dingding.service.DingService;
import org.apache.http.HttpEntity;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.entity.StringEntity;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import javax.crypto.Mac;
import javax.crypto.spec.SecretKeySpec;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.PrintWriter;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

@Service
public class DingServiceImpl implements DingService {
    public static Logger logger = LoggerFactory.getLogger(DingServiceImpl.class);

    @Value("${kt-watchdog.DING_TALK_WEB_HOOK}")
    private String DING_TALK_WEB_HOOK;

    /**
     * 发送POST请求，参数是Map, contentType=x-www-form-urlencoded
     *
     */
    public static String sendPost(String url, Map<String, Object> param) {
        Map<String, String> headParam = new HashMap();
        headParam.put("Content-type", "application/json;charset=UTF-8");
        PrintWriter out = null;
        BufferedReader in = null;
        String result = "";
        try {
            URL realUrl = new URL(url);
            // 打开和URL之间的连接
            URLConnection conn = realUrl.openConnection();
            // 设置通用的请求属性 请求头
            conn.setRequestProperty("accept", "*/*");
            conn.setRequestProperty("connection", "Keep-Alive");
            conn.setRequestProperty("user-agent",
                    "Fiddler");

            if (headParam != null) {
                for (Map.Entry<String, String> entry : headParam.entrySet()) {
                    conn.setRequestProperty(entry.getKey(), entry.getValue());
                }
            }
            // 发送POST请求必须设置如下两行
            conn.setDoOutput(true);
            conn.setDoInput(true);
            // 获取URLConnection对象对应的输出流
            out = new PrintWriter(conn.getOutputStream());
            // 发送请求参数
            out.print(JSON.toJSONString(param));
            // flush输出流的缓冲
            out.flush();
            // 定义BufferedReader输入流来读取URL的响应
            in = new BufferedReader(
                    new InputStreamReader(conn.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            logger.info("发送 POST 请求出现异常！" + e);
        }
        //使用finally块来关闭输出流、输入流
        finally {
            try {
                if (out != null) {
                    out.close();
                }
                if (in != null) {
                    in.close();
                }
            } catch (IOException ex) {
                ex.printStackTrace();
            }
        }
        return result;
    }

    private DateFormat  format = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Override
    public boolean sendDingTalk(String msg) {
        Map<String, Object> json = new HashMap<>();
        Map<String, Object> text = new HashMap<>();

        StringBuilder errorContentBuilder = new StringBuilder();
        errorContentBuilder
                .append(BusiConstant.CONTACT_HEADER_MSG)
                .append("，时间：")
                .append(format.format(new Date()))
                .append("\n\n")
                .append(msg);
        json.put("msgtype","text");
        text.put("content",errorContentBuilder.toString());
        json.put("text",text);
        JSONObject jsonObject = JSON.parseObject(sendPost(DING_TALK_WEB_HOOK, json));
        if (jsonObject.get("errcode").equals(0)) {
            return true;
        } else {
            logger.error("出错:"+jsonObject.toJSONString());
            return false;
        }
    }

}
